package io.renren.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class WeChatUtil {

    private static final Logger logger = LoggerFactory.getLogger(WeChatUtil.class);

    /**
     * @return 与企微服务器请求生成的accessToken
     */
    public static String requestAccessToken() {
        String accessToken = "";
        try {
            StringBuffer url = new StringBuffer("https://qyapi.weixin.qq.com/cgi-bin/gettoken");
            url.append("?corpid=").append("wxe2d11ecb2d76d98e");
            url.append("&corpsecret=").append("oIcfW4MZpfXeRKN7cYRsbqAsBmGEB5UCRfSnwzajOK8");
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(url.toString());
            httpPost.addHeader("Content-type", "application/json; charset=UTF-8");
            httpPost.setHeader("Accept", "application/json");
            HttpResponse response = httpClient.execute(httpPost);
            //获取返回
            HttpEntity entitys = response.getEntity();
            BufferedReader in = new BufferedReader(new InputStreamReader(entitys.getContent(), "UTF-8"));
            StringBuffer buffer = new StringBuffer();
            String line = null;
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            //打印返回的内容
            logger.info("调用获取企业微信token接口的响应参数：" + buffer.toString());
            JSONObject jsonObject = JSON.parseObject(buffer.toString());
            accessToken = jsonObject.get("access_token").toString();
        } catch (IOException e) {
            logger.error("调用获取企业微信token接口的异常信息:", e);
        }
        return accessToken;
    }

    /**
     * @param accessToken
     * @return 企微发送消息
     */

    public static String sendMessage(String accessToken, String message, String toUser) {
        try {
            Map<String, String> map = new HashMap<String, String>();
            map.put("content", message);
            JSONObject dataJson = new JSONObject();
            dataJson.put("msgtype", "text");
            dataJson.put("agentid", "1000135");
            dataJson.put("text", map);
            dataJson.put("touser", toUser);
            //打印请求参数
            String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-type", "application/json; charset=UTF-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity(new StringEntity(dataJson.toJSONString(), StandardCharsets.UTF_8));

            StringEntity entity;
            entity = new StringEntity(dataJson.toJSONString(), "UTF-8");
            httpPost.setEntity(entity);
            HttpResponse response;
            response = httpClient.execute(httpPost);

            //获取返回
            HttpEntity entitys = response.getEntity();
            BufferedReader in = new BufferedReader(new InputStreamReader(entitys.getContent(), StandardCharsets.UTF_8));
            StringBuilder buffer = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            //打印返回的内容
            logger.info("调用企业微信发送信息接口的响应参数：" + buffer);
            return buffer.toString();
        } catch (Exception e) {
            //日志记录异常信息
            logger.error("调用企业微信发送信息接口的异常信息:", e);
        }
        return "成功";
    }

}
